package com.matrixlearning.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.matrixlearning.mapper.ExamMapper;
import com.matrixlearning.pojo.Exam;
import com.matrixlearning.utils.GsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/test")
public class TestController {
    /**
     * Auther sun
     * DATE 2023/2/10 15:27
     * VERSION 1.0
     */

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    ExamMapper examMapper;

    @PostMapping("/test")
    public String test(@RequestBody String json) {
        Map reqMap = GsonUtils.fromJson(json, Map.class);
        String token = (String)reqMap.get("token");
        String point = (String)reqMap.get("point");
        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("point", point);
        List<Exam> exams = examMapper.selectList(queryWrapper);
        List<Map> list = new ArrayList<>();
        int i = 0;
        for (Exam exam: exams) {
            Map<String, String> map = new HashMap<>();
            map.put("id", String.valueOf(i++));
            map.put("title", exam.getTitle());
            list.add(map);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("exam", list);
        return GsonUtils.toJson(map);
    }

    @PostMapping("/submit")
    public String submit(@RequestBody String json) {
        Map reqMap = GsonUtils.fromJson(json, Map.class);
        Map answer = (Map)reqMap.get("answer");
        String point = (String)reqMap.get("point");
        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("point", point);
        List<Exam> exams = examMapper.selectList(queryWrapper);
        int grade = 0;
        for(int i=0;i<exams.size();i++) {
            int temp = (int)Math.round((Double)(answer.get(String.valueOf(i))));
            boolean b = exams.get(i).getAnswer().equals(String.valueOf(temp));
            if(b) {
                grade++;
            }
        }
        Map<String, Object> respMap = new HashMap<>();
        respMap.put("grade", grade);
        return GsonUtils.toJson(respMap);
    }
}
